package com.guaniu.voip.ui.main;

import static com.guaniu.voip.sip.SipManager.CALL_CONNECTED;
import static com.guaniu.voip.sip.SipManager.CALL_CONNECTING;
import static com.guaniu.voip.sip.SipManager.CALL_DISCONNECTED;
import static com.guaniu.voip.sip.SipManager.CALL_DISCONNECTED_FOR_USER_BUSY;
import static com.guaniu.voip.sip.SipManager.SIP_CALL_INCOMING;
import static com.guaniu.voip.sip.SipManager.SIP_CALL_OUTGOING;
import static com.guaniu.voip.sip.SipManager.SIP_REG_ONLINE;
import static com.guaniu.voip.ui.login.LoginActivity.PERMISSIONS_REQUEST_CODE;

import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle; 
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.guaniu.voip.BaseActivity;
import com.guaniu.voip.MyApplication;
import com.guaniu.voip.R;
import com.guaniu.voip.sip.Constant;
import com.guaniu.voip.sip.Ring;
import com.guaniu.voip.sip.SipManager;

import net.gotev.sipservice.BroadcastEventReceiver;
import net.gotev.sipservice.Logger;
import net.gotev.sipservice.MediaState;
import net.gotev.sipservice.SipServiceCommand;

import org.pjsip.pjsua2.pjsip_inv_state;


public class TryingCallActivity extends BaseActivity implements OnClickListener, BroadcastEventReceiver.SipEventObserver{
	private static final String TAG = "TryingCallActivity";
	private TextView mTvRemote;
	private View mTipAnswer;
	private ImageButton mBtPick;
	private ImageButton mBtHang;
	private ImageView mIvAvatar;
	
	private Intent mIntent;
	private KeyguardLock mKeyguardLock;
	private String mCallNumber;
	private boolean isOutGoing = false;
	private boolean isUserHangup = false;
	private boolean isHistoryCall = false;
	private int mMediaType;
	private int mCallId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_call_trying);

		
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
		
		getRemoteData();
		initView();
		startCallSession(isOutGoing);
	}

	@Override
	protected void onResume(){
		super.onResume();
		//初始化voip监听
		BroadcastEventReceiver.getBroadcastEventReceiver().registerEventObserverInner(this, this);
	}
	@Override
	protected void onStop() {
		super.onStop();
		Log.d(TAG,"onStop()");
		
		if(mKeyguardLock != null){
			mKeyguardLock.reenableKeyguard();
		}
	}
	
	private void initView(){
		mTipAnswer 	= findViewById(R.id.answer_layout);
		mTvRemote 	= (TextView)findViewById(R.id.view_call_trying_textView_remote);
		mBtPick 		= (ImageButton)findViewById(R.id.view_call_trying_imageButton_pick);
		mBtHang 		= (ImageButton)findViewById(R.id.view_call_trying_imageButton_hang);
		mIvAvatar 	= (ImageView)findViewById(R.id.view_call_trying_imageView_avatar);

		mBtPick.setOnClickListener(this);
		mBtHang.setOnClickListener(this);
		
		TextView tip = (TextView)findViewById(R.id.call_type);

		mTvRemote.setText(mCallNumber);
		if(mMediaType == Constant.MEDIA_TYPE_VIDEO){
			tip.setText(getString(R.string.rt_video));
		}else{
			tip.setText(getString(R.string.audio_call));			 
		}
		
		//add for lock screen. 
		final KeyguardManager keyguardManager = MyApplication.getKeyguardManager();
		if(keyguardManager != null){
			if(keyguardManager.inKeyguardRestrictedInputMode()){
				try{
					getWindow().setType(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
				}catch(Exception ex){
					Log.d(TAG, "ex:"+ex.getMessage());
				}
			}
			if(mKeyguardLock == null){
				mKeyguardLock = keyguardManager.newKeyguardLock(MyApplication.TAG);
			}
		}
	}
	
	private void getRemoteData(){
		mIntent = getIntent();
		isOutGoing = mIntent.getBooleanExtra(Constant.IS_MAKE_CALL, false);
		isHistoryCall = false;//mIntent.getBooleanExtra(Constant.IS_HISTORY_CALL, false);
		if (SipManager.getInstance().isOutGoingVideo()){
			mMediaType = Constant.MEDIA_TYPE_VIDEO;
		}else{
			mMediaType = Constant.MEDIA_TYPE_AUDIO;
		}
		mCallId = mIntent.getIntExtra(Constant.SESSION_ID, 0);
	}
	
	private void startCallSession(boolean isOutGoing){
		if(isOutGoing){ 
			// TODO Auto-generated method stub
			Log.d(TAG, "Start make call()");
			outGoing(mIntent);	 
		}else{
			inComing(mIntent);
		}
	}
	
	private void outGoing(Intent intent){
		String callN = intent.getStringExtra(Constant.CALL_NUMBER);
		if(TextUtils.isEmpty(callN))finish();
		mCallNumber = callN; 
		int callType;
		if(mMediaType == Constant.MEDIA_TYPE_VIDEO){
			callType = Constant.MEDIA_TYPE_VIDEO;// CALL_TYPE_LIVE
			SipManager.getInstance().setOutGoingVideo(true);
		}else{
			callType = Constant.MEDIA_TYPE_AUDIO;
			SipManager.getInstance().setOutGoingVideo(false);
		}
		boolean isVideo = SipManager.getInstance().isOutGoingVideo();

		//判断SIP是否连接
		if (SipManager.getInstance().getRegState() != SIP_REG_ONLINE) {
			showError("连接SIP服务器失败，请检查网络！");
		}else{
			SipManager.getInstance().setCallStatus(SIP_CALL_OUTGOING);

			SipServiceCommand.makeCall(TryingCallActivity.this,
					SipManager.getInstance().getAccount(), mCallNumber, isVideo, false);
		}
		setLayoutByCallType(true, callN);
	}
	
	private void inComing(Intent intent){
		String callNumber = intent.getStringExtra(Constant.CALL_NUMBER);
		isOutGoing = false;
		mCallId= intent.getIntExtra(Constant.SESSION_ID, 0);
		mMediaType= intent.getIntExtra(Constant.MEDIA_TYPE, 0);
		mCallNumber = callNumber;
//		setLayoutByCallType(false, callNumber);
	}
	
	private void setLayoutByCallType(boolean isOutGoing, String userName){
		if(isOutGoing){
			mBtPick.setVisibility(View.GONE);
			mTipAnswer.setVisibility(View.GONE);
		}else{
			mBtPick.setVisibility(View.VISIBLE);
		}
		mTvRemote.setText(userName);
	}

	@Override
	protected void onPause() {
		super.onPause();
		BroadcastEventReceiver.getBroadcastEventReceiver().unRegisterEventObserverInner(this);
	}
	@Override
	protected void onDestroy() {
		Log.d(TAG, "onDestroy()");
		super.onDestroy();


	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int vid = v.getId();
		switch(vid){
			case R.id.view_call_trying_imageButton_pick:
				pickHangCall(true);
				break;
			case R.id.view_call_trying_imageButton_hang:
				isUserHangup = true;
				pickHangCall(false);
				break;
			default:
				break;
		}
	}
	
	private void pickHangCall(boolean isPick){
		if (isPick){
			SipServiceCommand.acceptIncomingCall(this, SipManager.getInstance().getAccount(), mCallId, mMediaType==Constant.MEDIA_TYPE_AUDIO?false:true);

		}else{
			SipServiceCommand.declineIncomingCall(this, SipManager.getInstance().getAccount(), mCallId);
		}
	}
	private void inComingCall(int mediaType){
		Intent i2HomeActivity = null;
		if( SipManager.getInstance().isOutGoingVideo()){
			i2HomeActivity = new Intent(this,VideoChatActivity.class);
		}else{
			i2HomeActivity = new Intent(this,AudioChatActivity.class);
		}
		i2HomeActivity.putExtra(Constant.MEDIA_TYPE,mMediaType);
		i2HomeActivity.putExtra(Constant.CALL_NUMBER, mCallNumber);
		i2HomeActivity.putExtra(Constant.SESSION_ID, mCallId);
		i2HomeActivity.putExtra(Constant.IS_MAKE_CALL, false);
		startActivity(i2HomeActivity);
		finish();
	}
 
	
	private void outGoingCall(int mediaType){
		Intent i2HomeActivity = null;
		if( SipManager.getInstance().isOutGoingVideo()){
			i2HomeActivity = new Intent(this,VideoChatActivity.class);
		}else{
			i2HomeActivity = new Intent(this,AudioChatActivity.class);
		}
		i2HomeActivity.putExtra(Constant.MEDIA_TYPE,mMediaType);
		i2HomeActivity.putExtra(Constant.CALL_NUMBER, mCallNumber);
		i2HomeActivity.putExtra(Constant.SESSION_ID, mCallId);
		i2HomeActivity.putExtra(Constant.IS_MAKE_CALL, true);
//		i2HomeActivity.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		startActivity(i2HomeActivity);
		finish();
	}


	@Override
	public void notifyRegState(String account, int code, String reason, long expiration) {

	}

	@Override
	public void notifyIncomingCall(String accountID, int callID, String displayName, String remoteUri, boolean isVideo) {

	}

	@Override
	public void notifyCallState(String accountID, int callID, int callStateCode, int callStatusCode, long connectTimestamp) {
		if (pjsip_inv_state.PJSIP_INV_STATE_CALLING==callStateCode) {
			Toast.makeText(this, "呼叫中,请等待", Toast.LENGTH_SHORT).show();
			//呼出
			SipManager.getInstance().setCallStatus(SIP_CALL_OUTGOING);
		} else if (pjsip_inv_state.PJSIP_INV_STATE_INCOMING==callStateCode) {
			//来电
			SipManager.getInstance().setCallStatus(SIP_CALL_INCOMING);
		} else if (pjsip_inv_state.PJSIP_INV_STATE_EARLY==callStateCode) {
			//响铃
		} else if (pjsip_inv_state.PJSIP_INV_STATE_CONNECTING==callStateCode) {
			//连接中
		} else if (pjsip_inv_state.PJSIP_INV_STATE_CONFIRMED==callStateCode) {
			//连接成功
			SipManager.getInstance().setCallStatus(CALL_CONNECTED);
			mCallId = callID;
			if (isOutGoing){
				outGoingCall(mMediaType);
			}else{
				inComingCall(mMediaType);
			}

		} else if (pjsip_inv_state.PJSIP_INV_STATE_DISCONNECTED==callStateCode) {
			if (SipManager.getInstance().getCallStatus() == SIP_CALL_OUTGOING){
				Toast.makeText(this, "呼叫失败", Toast.LENGTH_SHORT).show();
			}else {
			}
			Ring.getInstance(TryingCallActivity.this).stopRingTone();
			SipManager.getInstance().setCallStatus(CALL_DISCONNECTED);

			finish();
		} else if (pjsip_inv_state.PJSIP_INV_STATE_NULL==callStateCode) {
			//未知错误

		}
	}

	@Override
	public void notifyCallMediaState(String accountID, int callID, MediaState stateType, boolean stateValue) {

	}

	@Override
	public void notifyChangeNetwork() {

	}
	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);

		if (requestCode != PERMISSIONS_REQUEST_CODE) {
			showError("请在设置中容许相应权限！");

		}
	}
}
